package com.example.demo.service.impl;

import com.example.demo.domain.vo.ProcessInstanceVO;
import com.example.demo.service.ChooseProcessService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.spring.integration.Activiti;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author: zsg
 * @Date: 2018/07/10 16:25
 */
@Service
public class ChooseProcessServiceImpl implements ChooseProcessService {

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private IdentityService identityService;

    @Autowired
    private TaskService taskService;

    /**
     * 开启一个流程
     * @param processKey
     * @param userId
     * @param message
     * @return
     */
    @Override
    public  List<ProcessInstanceVO> startProcess(String processKey, String userId, String message) {

        Map<String,Object> variables = new HashMap<>();
        variables.put("message",message);

        //记录流程发起人
        identityService.setAuthenticatedUserId(userId);

        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processKey, variables);

        List<Task> list = taskService.createTaskQuery().processInstanceId(processInstance.getId()).list();

        List<ProcessInstanceVO> voList = new ArrayList<>();
        list.forEach(task -> {
            ProcessInstanceVO processInstanceVO = new ProcessInstanceVO();
            processInstanceVO.setDeploymentId(processInstance.getDeploymentId());
            processInstanceVO.setId(processInstance.getId());
            processInstanceVO.setProcessDefinitionId(processInstance.getProcessDefinitionId());
            processInstanceVO.setName(processInstance.getName());
            processInstanceVO.setActivityId(processInstance.getActivityId());
            processInstanceVO.setProcessDefinitionName(processInstance.getProcessDefinitionName());
            processInstanceVO.setTaskId(task.getId());
            processInstanceVO.setTaskName(task.getName());
            voList.add(processInstanceVO);
        });

        return voList;
    }
}
